package org.speedmall.business.amount.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.speedmall.amount.api.bo.AmountDecreaseBO;
import org.speedmall.amount.api.bo.AmountIncreaseBO;
import org.speedmall.business.amount.core.entity.Account;
import org.speedmall.business.amount.core.mapper.AmountMapper;
import org.speedmall.business.amount.core.service.AmountService;
import org.speedmall.common.core.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author hujiaguo
 * @Package org.speedmall.business.amount.core.service
 * @date 2024/4/25 16:34:57
 */
public class AmountServiceImpl implements AmountService {

    @Autowired
    private AmountMapper amountMapper;
    @Override
    public void increaseAmount(AmountIncreaseBO increaseBO) {
        Account account = new Account();
        account.setUserId(increaseBO.getUserId());
        account = findByParma(account);

        account.setTotal(account.getTotal().add(increaseBO.getAmount()));
        account.setResidue(account.getResidue().add(increaseBO.getAmount()));

        amountMapper.updateById(account);
    }

    @Override
    public void decreaseAmount(AmountDecreaseBO decreaseBO) {
        Account account = new Account();
        account.setUserId(decreaseBO.getUserId());
        account = findByParma(account);

        if (account.getResidue().compareTo(decreaseBO.getAmount()) < 0) {
            throw new BusinessException("账户可用余额不足，请充值");
        }
        account.setResidue(account.getResidue().subtract(decreaseBO.getAmount()));

        amountMapper.updateById(account);
    }

    @Override
    public Account findById(Long id) {
        return amountMapper.selectById(id);
    }

    @Override
    public Account findByParma(Account account) {
        Wrapper<Account> wrapper = new QueryWrapper<>(account);
        return amountMapper.selectOne(wrapper);
    }
}
